<?php
namespace app\admin\controller;

class JurisdictionGroup extends Common
{

    private $obj;

    public function _initialize()
    {
        parent::_initialize();
        $this->obj = model('JurisdictionGroup');
    }

    /**
     * 角色列表
     * @return mixed
     */
    public function index()
    {
        /**
         * 获取管理员列表
         */
        $data = $this->obj->getRoleList();
        $this->assign('data', $data);
        return view();
    }

    /**
     * 保存角色数据
     */
    public function save_role() {
        $id = input('param.id', 0);
        if (request()->isPost()) {
            /**
             * 组装数据
             */
            $data['name'] = input('post.name', '');

            /**
             * 验证数据
             */
            $validate = validate('JurisdictionGroup');
            if(!$validate->check($data)) {
                $this->error($validate->getError());
            }

            /**
             * 检查角色名是否存在
             */
            $where['id'] = $id > 0 ? ['neq', $id] : ['neq', 0];
            $where['name'] = $data['name'];
            $role = $this->obj->getRole($where);
            if ($role) {
                $this->error('角色名已存在');
            }

            /**
             * 保存数据
             */
            $where = $id > 0 ? ['id' => $id] : [];
            $rs = $this->obj->save($data, $where);

            // 清理缓存
            \app\api\service\Base::clear_cache();

            if ($rs) {
                $this->success('保存成功');
            } else {
                $this->error('保存失败');
            }
        } else{
            $data =[];
            if ($id > 0) {
                $where['id'] = $id;
                $data = $this->obj->getRole($where);
            }
            $this->assign('data', $data);
            return view();
        }
    }

    /**
     * 设置权限组权限
     * @return mixed
     */
    public function save_jurisdiction() {
        $id = input('param.id');
        if (request()->isPost()) {
            $jurisdiction = input('param.jurisdiction/a');
            $jurisdiction = $jurisdiction ? implode(',', $jurisdiction) : '';
            $rs = $this->obj->save(['jurisdiction' => $jurisdiction], ['id' => $id]);

            // 清理缓存
            \app\api\service\Base::clear_cache();

            if ($rs) {
                $this->success('设置成功', null, '', 1);
            } else {
                $this->error('设置失败');
            }
        } else {
            $this->assign('id', $id);
            $menu = config('menu');
            $this->assign('menu', $menu);
            $data = $rs = $this->obj->get(['id' => $id]);
            $jurisdiction = explode(',', $data['jurisdiction']);
            $this->assign('jurisdiction', $jurisdiction);
            return view();
        }
    }
}
